package com.mingqijia.gassafety.job.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.influxdb.client.domain.Run;
import com.mingqijia.gassafety.db.entity.RunningStrategyExt;
import com.mingqijia.gassafety.db.entity.RunningStrategyReport;
import com.mingqijia.gassafety.db.entity.WarningRecord;
import com.mingqijia.gassafety.db.mapper.RunningStrategyReportMapper;
import com.mingqijia.gassafety.db.mapper.WarningAlarmMapper;
import com.mingqijia.gassafety.db.mapper.WarningRecordMapper;
import com.mingqijia.gassafety.job.dto.CallTaskDTO;
import com.mingqijia.gassafety.job.service.AicallTaskService;
import com.mingqijia.gassafety.shared.constant.CallTypeEnum;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName CallTaskServiceImpl.java
 * @Description 呼叫任务
 * @createTime 2023年02月15日
 */
@Service
@Slf4j
public class CallTaskServiceImpl {

    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    XFCallServiceImpl xFCallService;
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    WarningAlarmMapper warningAlarmMapper;
    @Autowired
    WarningRecordMapper warningRecordMapper;
    @Autowired
    WarningRecordServiceImpl recordService;
    @Autowired
    RunningStrategyServiceImpl runningStrategyJob;
    @Autowired
    RunningStrategyReportMapper reportMapper;

    @Autowired
    AicallTaskService aicallTaskService;
    
    public Map<String, Object> sendCallTask(String spId, Set<String> phones, String imei, Integer type, String conId, RunningStrategyExt ext) {
        log.info("sendCallTask-外呼入参:spId:{},phones:{},imei:{}",
                spId, JSONObject.toJSONString(phones), imei);
        if (type!=null&&type==2&& !StringUtil.isEmpty(conId)){
            LambdaQueryWrapper<RunningStrategyReport> wrapper = new LambdaQueryWrapper<>();
            wrapper.or().eq(RunningStrategyReport::getIsDeleted,0)
                    .eq(RunningStrategyReport::getConsumerId,conId)
                    .orderByDesc(RunningStrategyReport::getReportDate);
            List<RunningStrategyReport> reports = reportMapper.selectList(wrapper);
            log.info("sendCallTask-reports:{}",JSONObject.toJSONString(reports));
            if (!CollectionUtils.isEmpty(reports))imei=reports.get(0).getIMEI();
        }
        if (imei.contains("-")&&imei.split("-").length>=3){
            String[] split = imei.split("-");
            imei=split[0];
        }
        log.info("sendCallTask-imei:{}",imei);
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> dtuInfos = equipmentService.selectByImei(imei, spId);
        Map<String, Object> paramMap = new HashMap<>();
        log.info("sendCallTask-selectByImei:{}", JSONObject.toJSONString(dtuInfos));
        CallTaskDTO callTaskDTO = new CallTaskDTO();
        List<JSONArray> calls = new ArrayList<>();
        if (dtuInfos == null&&(type==null||type!=2)) return null;
        String address = "";
        Object position = dtuInfos.get("installationPosition");
        if (Integer.parseInt(dtuInfos.get("templateType") + "") == 2) {
            address = dtuInfos.get("address") + "";
        } else {
            address = dtuInfos.get("custAddress") + "";
        }
        if (!StringUtils.isEmpty(address)) {
            address = "地址是在" + address;
            if (!StringUtils.isEmpty(position)) address = address + "(" + position + ")";
        }else {
            address="";
        }
        List<String> phoneList = new ArrayList<>();
        phones.forEach(s -> {
            phoneList.add(s);
        });
        Object name = dtuInfos.get("name");
        Object paramValue = dtuInfos.get("paramValue");
        Object factoryName = "";
        paramMap.put("name",name);
        paramMap.put("phone",paramValue);
        paramMap.put("address",address);

        callTaskDTO = aicallTaskService.getAicallTaskByType(type,spId);

        boolean hasFactoryName = false;
        if ( null!=callTaskDTO.getRobotContent() && callTaskDTO.getRobotContent().contains("#factoryName#") ){
            factoryName = equipmentService.getEquipmentManufacturerName(
                    null==dtuInfos.get("equipmentManufacturer")?"":dtuInfos.get("equipmentManufacturer").toString(),
                    spId
            );
            paramMap.put("factoryName",factoryName);
            callTaskDTO.getCallColumn().add("厂家名称");
            hasFactoryName = true;
        }

        for (String phone : phoneList) {
            if (phone.contains("-"))phone = phone.replace("-", "");
            JSONArray array = new JSONArray();
            if (type==null)array.add(0, phone);
            if (type!=null)array.add(0, name);
            array.add(1, address);
            array.add(2, name);
            if (type==null||type!=2) array.add(3, paramValue);
            if (type!=null&&type==2) array.add(3, DateUtil.format(DateUtil.offsetMonth(new Date(), -1), "yyyy-MM"));
            if (type!=null)array.add(4, phone);
            if( hasFactoryName ){
                array.add(array.size(), factoryName);
            }
            calls.add(array);
        }

        callTaskDTO.setCallList(calls);

        callTaskDTO = xFCallService.addCallExecTimeParam(callTaskDTO,ext);

        JSONObject jsonObject = null;
        try {
            jsonObject = xFCallService.callPoolCreate(callTaskDTO,spId);
        } catch (Exception e) {
            log.error("xFCallService-callCreate:{}",e);
            //res.put("errMsg",e.getMessage());
        }
        log.info("callTaskDetail-callCreate:{}", JSONObject.toJSONString(jsonObject));
        JSONArray data =null;
        if (jsonObject != null ) {
             data = jsonObject.getJSONArray("call_ids");
            log.info("callTaskDetail-saveCallList:dtuInfos:{},data:{},spid:{}" +
                            "", JSONObject.toJSONString(dtuInfos)
                    , JSONObject.toJSONString(data), JSONObject.toJSONString(spId));

        }

        res.put("robotContent", callTaskDTO.getRobotContent());
        res.put("data", data);
        res.put("dtuInfos", dtuInfos);
        res.put("phoneList", phoneList);
        res.put("paramMap", paramMap);
        return res;
    }

    /**
     * 存储外呼记录
     *
     * @param data
     * @param phones
     * @return
     */
    public boolean saveCallList(JSONArray data, Map<String, Object> dtuInfos, Map<String, Object> paramMap,List<String> phones,
                                String spId, String iMEI,
                                Integer value, int report, String con, Object strategyId,
                                Integer level, Date date, int sendType, long snowflakeId, int sendResult,
                                String supIMEI,
                                String info, Map<String, Integer> objectTypeMap,Integer type, String robotContent,
                                String errMsg) {

        try {
            for (int i = 0; i < phones.size(); i++) {
                if (type==null){
                    String content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                    saveWarningRecord(spId, iMEI, value, report, con,
                            strategyId, level, date, sendType, snowflakeId, sendResult, content, supIMEI, errMsg,
                            data!=null?data.get(i) + "":"", phones.get(i) + "", objectTypeMap.get(phones.get(i)), info);
                }else {
                    String content ="";
                    if (type==0){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_OFFLINE:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }else if (type==1){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_BREAKDOWN:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }else if (type==2){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_REPORT:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#date#", DateUtil.format(DateUtil.offsetMonth(new Date(), -1), "yyyy-MM"))
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }else if (type==3){
                        content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_SERVICE_PERIOD:robotContent)
                                .replace("#name#", paramMap.get("name") + "")
                                .replace("#address#", paramMap.get("address")+"")
                                .replace("#phone#", paramMap.get("phone")+"")
                                .replace("#verb#", paramMap.get("verb")+"")
                                .replace("#date#", paramMap.get("date")+"")
                                .replace("#factoryName#", paramMap.get("factoryName")+"");
                    }

                    runningStrategyJob.saveWarningRecord(spId, iMEI, report, con,
                            strategyId, String.valueOf(level), date, sendType, snowflakeId, sendResult, content, supIMEI, errMsg,
                            data!=null?data.get(i) + "":"", phones.get(i) + "", 0, info);
                }
            }
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    /**
     * 存储外呼记录
     *
     * @param data
     * @param phones
     * @return
     */
    public boolean saveCallInformList(JSONArray data, Map<String, Object> dtuInfos, Map<String, Object> paramMap,List<String> phones,
                                String spId, String iMEI,
                                Integer value, int report, String con, Object strategyId,
                                String level, Date date, int sendType, long snowflakeId, int sendResult,
                                String supIMEI,
                                String info, Map<String, Integer> objectTypeMap,Integer type, String robotContent,
                                String errMsg) {

        try {
            for (int i = 0; i < phones.size(); i++) {
                String content ="";
                if (type==0){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_OFFLINE:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }else if (type==1){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_BREAKDOWN:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }else if (type==2){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_MESSAGES_REPORT:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#date#", DateUtil.format(DateUtil.offsetMonth(new Date(), -1), "yyyy-MM"))
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }else if (type==3){
                    content = (StringUtils.isEmpty(robotContent)?Constants.WARNING_CALL_SERVICE_PERIOD:robotContent)
                            .replace("#name#", paramMap.get("name") + "")
                            .replace("#address#", paramMap.get("address")+"")
                            .replace("#phone#", paramMap.get("phone")+"")
                            .replace("#verb#", paramMap.get("verb")+"")
                            .replace("#date#", paramMap.get("date")+"")
                            .replace("#factoryName#", paramMap.get("factoryName")+"");
                }

                runningStrategyJob.saveWarningRecord(spId, iMEI, report, con,
                        strategyId, level, date, sendType, snowflakeId, sendResult, content, supIMEI, errMsg,
                        data!=null?data.get(i) + "":"", phones.get(i) + "", 0, info);
            }
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    public void saveWarningRecord(String spId, String iMEI,
                                  Integer value, int report, String con, Object strategyId,
                                  Integer level, Date date, int sendType, long snowflakeId, int sendResult,
                                  String content, String supIMEI, Object errorMsg,
                                  String receiptCode, String telephone, int type, String info) {
        WarningRecord warningRecord = new WarningRecord();
        warningRecord.setConsumerId(con);
        warningRecord.setStartTime(date);
        warningRecord.setWarningStartTime(date);
        warningRecord.setTriggerRuleId(strategyId + "");
        warningRecord.setIMEI(iMEI);
        warningRecord.setTaskIdentificationCode(snowflakeId + "");
        warningRecord.setConcentration(value + "");
        warningRecord.setType(report);
        warningRecord.setSendType(sendType);
        warningRecord.setObjLevel(level);
        warningRecord.setSpId(spId);
        warningRecord.setSendResult(sendResult);
        warningRecord.setContent(content);
        warningRecord.setReceiptCode(receiptCode);
        warningRecord.setNotifyObjInfo(info);
        warningRecord.setNotifyObjType(type);
        warningRecord.setPushPhone(telephone);
        warningRecord.setSupIMEI(supIMEI);
        warningRecord.setNotifyFrom(0);
        warningRecord.setRemark(!StringUtils.isEmpty(errorMsg)?errorMsg + "":"发送成功");

        log.info("saveWarningRecord:{}", JSONObject.toJSONString(warningRecord));
        warningRecordMapper.insert(warningRecord);
    }

}